package cn.com.hhrcw.utils.huawei;

import cn.com.hhrcw.constant.CommonConstant;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotBlank;

/**
 * @author lixingxing
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@Component
public class HWMeetUtil {

    private static final String CHINA_URL = "api.meeting.huaweicloud.com";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * AppId方式进行鉴权  返回token等信息
     *
     * @param authorization header:Authorization 携带应用鉴权信息。
     *                      规则：HMAC-SHA256 signature=HexEncode(HMAC256((appId + ":" + userId + ":" + expireTime + ":" + nonce), appKey))
     *                      样例：HMAC-SHA256 signature=07f31aa9eafb06652c6899248b145c1a3264242e2ccf4c81b1b6eb99bb5c
     * @param contentType   header:Content-Type BODY的媒体格式（样例：application/json; charset=UTF-8）
     * @param appId         App ID
     * @param clientType    登录帐号类型。
     *                      0：第三方Web客户端；
     *                      50：第三方手机客户端；
     *                      51：第三方PAD客户端；
     *                      52：第三方PC客户端；
     *                      53：第三方电视客户端；
     *                      54：第三方大屏客户端。
     * @param expireTime    应用鉴权信息过期时间戳，单位秒。
     * @param nonce         随机字符串，用于计算应用鉴权信息。
     *                      maxLength：255
     *                      minLength：1
     * @param userId        用户ID。（当userId字段未携带或值为空字符串时，当作企业默认管理员登录）
     * @return
     */
    public String appAuth(String authorization, String contentType, String appId,
                          Integer clientType, Long expireTime,
                          String nonce, String userId) {

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Authorization", authorization);
        requestHeaders.add("Content-Type", contentType);
        //body
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("appId", appId);
        requestBody.add("clientType", String.valueOf(clientType));
        requestBody.add("expireTime", String.valueOf(expireTime));
        requestBody.add("nonce", nonce);
        requestBody.add("userId", userId);
        //HttpEntity
        HttpEntity<?> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
        //post
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(CHINA_URL + "/v2/usg/acs/auth/appauth", requestEntity, String.class);
        if (HttpStatus.OK == responseEntity.getStatusCode()) {
            return responseEntity.getBody();
        }
        return null;
    }

    /**
     * 刷新token
     *
     * @param xAccessToken token
     * @return
     */
    public String updateToken(String xAccessToken) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add(CommonConstant.TOKEN, xAccessToken);
        //HttpEntity
        HttpEntity<?> requestEntity = new HttpEntity<>(null, requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(CHINA_URL + "/v1/usg/acs/token", HttpMethod.PUT, requestEntity, String.class);
        if (HttpStatus.OK == response.getStatusCode()) {
            return response.getBody();
        }
        return null;
    }

    /**
     * 校验Token
     *
     * @param contentType     BODY的媒体格式（样例：application/json; charset=UTF-8）
     * @param token
     * @param needGenNewToken 是否生成新的token。
     *                        true：生成新的token值。
     *                        false：不生成新的token值。
     * @return
     */
    public String checkToken(String contentType, String token, boolean needGenNewToken) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", contentType);
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("token", token);
        requestBody.add("needGenNewToken", needGenNewToken);
        //HttpEntity
        HttpEntity<?> requestEntity = new HttpEntity<>(requestBody, requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(CHINA_URL + "/v1/usg/acs/token/validate", HttpMethod.POST, requestEntity, String.class);
        if (HttpStatus.OK == response.getStatusCode()) {
            return response.getBody();
        }
        return null;
    }

    /**
     * 删除token
     *
     * @param xAccessToken token
     * @return
     */
    public String deleteToken(String xAccessToken) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add(CommonConstant.TOKEN, xAccessToken);
        HttpEntity<?> requestEntity = new HttpEntity<>(null, requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(CHINA_URL + "/v1/usg/acs/token", HttpMethod.DELETE, requestEntity, String.class);
        if (HttpStatus.OK == response.getStatusCode()) {
            return response.getBody();
        }
        return null;
    }

    /**
     * 创建会议
     *
     * @param token token
     * @param body  创建会议参数 参考CreateMeetingParam.java
     * @return
     */
    public String createMeeting(String token, @NotBlank CreateMeetingParam body) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add(CommonConstant.TOKEN, token);
        //HttpEntity
        Gson gson = new Gson();
        HttpEntity<String> requestEntity = new HttpEntity<>(gson.toJson(body), requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(CHINA_URL + "/v1/mmc/management/conferences", HttpMethod.POST, requestEntity, String.class);
        if (HttpStatus.OK == response.getStatusCode()) {
            return response.getBody();
        }
        return null;
    }

    /**
     * 删除会议
     *
     * @param conferenceID 会议id
     * @param token        token
     * @return
     */
    public String deleteMeeting(String conferenceID, String token) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add(CommonConstant.TOKEN, token);
        HttpEntity<?> requestEntity = new HttpEntity<>(null, requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(CHINA_URL + "/v1/mmc/management/conferences?conferenceID=" + conferenceID, HttpMethod.DELETE, requestEntity, String.class);
        boolean b = HttpStatus.OK == response.getStatusCode();
        return b ? response.getBody() : null;
    }

}
